package com.deshan.websys.code.utils;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.URL;
import java.net.UnknownHostException;

import javax.servlet.http.HttpServletRequest;

import lombok.extern.slf4j.Slf4j;

/**
 * IP工具类
 * 
 * @author Administrator
 *
 */
@Slf4j
public class IpUtils {
	private static final String UNKNOWN = "unknown";
	private static final String LOCALHOST_IP = "127.0.0.1";
	// 客户端与服务器同为一台机器，获取的 ip 有时候是 ipv6 格式
	private static final String LOCALHOST_IPV6 = "0:0:0:0:0:0:0:1";
	private static final String SEPARATOR = ",";

	// 根据 HttpServletRequest 获取 IP
	public static String getIpAddress(HttpServletRequest request) {
		if (request == null) {
			return "unknown";
		}
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
			ip = request.getHeader("X-Forwarded-For");
		}
		if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
			ip = request.getHeader("X-Real-IP");
		}
		if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
			if (LOCALHOST_IP.equalsIgnoreCase(ip) || LOCALHOST_IPV6.equalsIgnoreCase(ip)) {
				// 根据网卡取本机配置的 IP
				InetAddress iNet = null;
				try {
					iNet = InetAddress.getLocalHost();
				} catch (UnknownHostException e) {
					e.printStackTrace();
				}
				if (iNet != null)
					ip = iNet.getHostAddress();
			}
		}
		// 对于通过多个代理的情况，分割出第一个 IP
		if (ip != null && ip.length() > 15) {
			if (ip.indexOf(SEPARATOR) > 0) {
				ip = ip.substring(0, ip.indexOf(SEPARATOR));
			}
		}
		return LOCALHOST_IPV6.equals(ip) ? LOCALHOST_IP : ip;
	}

	/**
	 * 获取ip地址
	 */
	public static String getIpAddress2(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("HTTP_CLIENT_IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("HTTP_X_FORWARDED_FOR");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		// 本机访问
		if ("localhost".equalsIgnoreCase(ip) || "127.0.0.1".equalsIgnoreCase(ip)
				|| "0:0:0:0:0:0:0:1".equalsIgnoreCase(ip)) {
			// 根据网卡取本机配置的IP
			InetAddress inet;
			try {
				inet = InetAddress.getLocalHost();
				ip = inet.getHostAddress();
			} catch (UnknownHostException e) {
				e.printStackTrace();
			}
		}
		// 对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
		if (null != ip && ip.length() > 15) {
			if (ip.indexOf(",") > 15) {
				ip = ip.substring(0, ip.indexOf(","));
			}
		}
		return ip;
	}

	/**
	 * 获取mac地址
	 */
	public static String getMacAddress() throws Exception {
		// 取mac地址
		byte[] macAddressBytes = NetworkInterface.getByInetAddress(InetAddress.getLocalHost()).getHardwareAddress();
		// 下面代码是把mac地址拼装成String
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < macAddressBytes.length; i++) {
			if (i != 0) {
				sb.append("-");
			}
			// mac[i] & 0xFF 是为了把byte转化为正整数
			String s = Integer.toHexString(macAddressBytes[i] & 0xFF);
			sb.append(s.length() == 1 ? 0 + s : s);
		}
		return sb.toString().trim().toUpperCase();
	}

	/**
	 * 获取公网IP
	 * 
	 * @return
	 */
	public static String getOutIP() {
		try {
			URL whatismyip = new URL("http://checkip.amazonaws.com");
			BufferedReader in = new BufferedReader(new InputStreamReader(whatismyip.openStream()));

			String ip = in.readLine();
			return ip;

		} catch (Exception e) {
			log.info("getOutIP()---获取公网IP失败");
		}
		return "";
	}

}
